const Mock = require("mockjs");
const bodyParser = require("body-parser");
const JWT = require("jsonwebtoken");
const key = "qikfwkedl;qowd;q/";
const userList = [
  {
    username: "admin",
    password: "admin",
    nickname: "管理员",
  },
  {
    username: "123123@qq.com",
    password: "666666",
    nickname: "张三",
  },
];
const { list } = Mock.mock({
  "list|40": [
    {
      title: "@ctitle",
      url: "@image(120x80, @color)",
      id: "@id",
      "price|10-100": 1,
    },
  ],
});

module.exports = (app) => {
  app.use(bodyParser.json());

  app.get("/api/list", (req, res) => {
    res.send({
      code: 200,
      data: list,
    });
  });

  app.post("/api/detail", (req, res) => {
    const { id } = req.body;
    const result = list.find((v) => v.id === id);

    if (result) {
      res.send({
        code: 200,
        data: result,
      });
    } else {
      res.send({
        code: 404,
        data: null,
        message: "该商品已经下架！！",
      });
    }
  });

  app.post("/api/login", (req, res) => {
    const { username, password } = req.body;
    const result = userList.find(
      (v) => v.username === username && password === v.password
    );

    if (result) {
      res.send({
        code: 200,
        data: {
          nickname: result.nickname,
          username: result.username,
          token: JWT.sign(
            {
              nickname: result.nickname,
              username: result.username,
            },
            key
          ),
        },
        message: "登录成功",
      });
    } else {
      res.send({
        code: 403,
        message: "登录失败， 重新你登录",
      });
    }
  });
};
